package com.sprite.framework.entity.idgenerator;

import java.util.HashMap;
import java.util.Map;

import com.sprite.framework.entity.IdGenerator;
import com.sprite.utils.SnowflakeWorker;

/**
 * 雪花算法生成器
 * @author Jack
 */
public class SnowflakeGenerator implements IdGenerator{

	// key is entityName
	private Map<String, SnowflakeWorker> workers = new HashMap<>();

	private long workerId;
	private long datacenterId;


	@Override
	public String name() {
		return "snowflake";
	}

	@Override
	public String nextId(String entityName) {
		SnowflakeWorker worker = workers.get(entityName);
		if(worker == null) {
			synchronized (worker) {
				SnowflakeWorker workerB = new SnowflakeWorker(workerId, datacenterId);
				worker = workers.putIfAbsent(entityName, workerB);
				if(worker == null) {
					worker = workerB; 
				}
			}
		}
		return worker.nextId()+"";
	}


	public long getWorkerId() {
		return workerId;
	}


	public void setWorkerId(long workerId) {
		this.workerId = workerId;
	}


	public long getDatacenterId() {
		return datacenterId;
	}


	public void setDatacenterId(long datacenterId) {
		this.datacenterId = datacenterId;
	}

}
